package com.tsing.cli.common.core.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定时任务配置类
 *
 * @author TheTsing
 */
@Slf4j
@EnableScheduling
@AutoConfiguration
public class ScheduleConfiguration implements SchedulingConfigurer {

    private static final int CORE = Runtime.getRuntime().availableProcessors() + 1;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(CORE);
        executor.setThreadNamePrefix("task-thread-");
        executor.setErrorHandler(t -> log.error(t.getMessage(), t));
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        taskRegistrar.setTaskScheduler(executor);
    }

}
